package com.gopay.bis.manager.bank.ebank;

import java.util.Map;

import javax.annotation.Resource;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.bis.common.util.TransUtils;
import com.gopay.bis.dao.payconfig.BisBankExtConfigDAO;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.hnapay.ebank.HnaPayMessage;
import com.gopay.common.domain.bank.hnapay.ebank.query.HnaPayMessageQuery;
import com.gopay.common.domain.bis.BaseBisBankExtConfig;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.KeyUtil;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

/**
 * 新生在线网银直连对象封装
 * 
 * @HnaPayManager.java
 * @author LiLiLi
 */
public class HnaPayManager implements BankManagerRemoteService {
	private String separate=",";
	
	@Resource(name = "hnaPayConfig")
	private Map<String, String> hnaPayConfig;
	
	@Resource(name = "hnaPayBankServiceClient")
	private BankService hnaPayBankServiceClient;
		
	@Resource(name="bisBankExtConfigDAO")
	private BisBankExtConfigDAO bisBankExtConfigDAO;
	
	@Override
	public Object sign(BaseMessage msg) throws GopayException {
		// 获取银行接口通道配置信息 
	    // 该字段无用 add by zhengxue
//		BaseBisBankExtConfig bankConfig = bisBankExtConfigDAO.findExtConfigByBankCodeAndBankBusProd(msg.getBankBusProd(), msg.getBank());
		msg.setBankOrderId("HN" + TransUtil.processOrderIdTo14Digit(msg.getOrderId()));
		//设置新生接口银行码
//		msg.setSpecial2(bankConfig.getIntrfaceBankCode());
		HnaPayMessage message = (HnaPayMessage)msg;
		message.setBankUrl(message.getPayUrl());
		message.setVersion(hnaPayConfig.get("HNAPAY.VERSION"));
		message.setType(hnaPayConfig.get("HNAPAY.TYPE"));
		message.setPayType(hnaPayConfig.get("HNAPAY.PAYTYPE"));
		message.setCurrencyCode(hnaPayConfig.get("HNAPAY.CURRENCYCODE"));
		message.setDirectFlag(hnaPayConfig.get("HNAPAY.DIRECTFLAG"));
		message.setBuyerMarked("384187312@qq.com");
		message.setBorrowingMarked(hnaPayConfig.get("HNAPAY.BORROWINGMARKED"));
		message.setOrgCode(message.getSpecial2());
		message.setPartnerID(hnaPayConfig.get("HNAPAY."+message.getOrgCode().toUpperCase()+".PARTERID"));
		message.setReturnUrl(message.getPayNotifyUrl());
		message.setNoticeUrl(message.getPayRuturnUrl());
		message.setCharset(hnaPayConfig.get("HNAPAY.CHARSET"));
		message.setSignType(hnaPayConfig.get("HNAPAY.SIGNTYPE"));
		message.setSubmitTime(message.getOrderDate());
		message.setSerialID("gfbpay"+System.nanoTime());
		message.setRemark(hnaPayConfig.get("HNAPAY.REMARK"));
		// 订单金额，单位：分，金额为大于0的正整数
		message.setOrderAmount(TransUtils.amountConvert2Fen(message.getAmount()
				.toString()));
		message.setGoodsName(hnaPayConfig.get("HNAPAY.GOODSNAME"));
		message.setGoodsCount("1");
		//组装orderDetails
		StringBuffer sb = new StringBuffer();
		sb.append(message.getBankOrderId()).append(separate)
		.append(message.getOrderAmount()).append(separate)
		.append(message.getDisplayName()).append(separate)
		.append(message.getGoodsName()).append(separate)
		.append(message.getGoodsCount());
		
		message.setOrderDetails(sb.toString());
		
		message.setTotalAmount(message.getOrderAmount());
		// 构建签名所需明文
		message.setPlainMessage(buildSignMessage(message));
        BankLogUtils.printB2CManagerSignSendLog(message);
		// 发送签名
		String signMsg = (String) hnaPayBankServiceClient.sign(message);
		message.setSignMsg(signMsg);
		BankLogUtils.printB2CManagerSignReturnLog(message);
		return message;
	}

	@Override
	public Object verify(BaseMessage msg) throws GopayException {
		HnaPayMessage message = (HnaPayMessage)msg;
		String plainMessage = buildVerifyPlain(message);
		message.setPlainMessage(plainMessage);
		BankLogUtils.printB2CManagerVerifySendLog(message);
		// 发送验签
		boolean flag = (Boolean) hnaPayBankServiceClient.verify(message);
		BankLogUtils.printB2CManagerVerifyReturnLog(message, flag);
		return flag;
	}

	@Override
	public Object query(Object obj) throws GopayException {
		HnaPayMessageQuery message = (HnaPayMessageQuery)obj;
		message.setVersion(hnaPayConfig.get("HNAPAY.VERSION"));
		message.setSerialID("gfbquery"+System.nanoTime());
		message.setMode(hnaPayConfig.get("HNAPAY.MODE"));
		message.setQueryType(hnaPayConfig.get("HNAPAY.QUERYTYPE"));
		message.setRemark(hnaPayConfig.get("HNAPAY.REMARK"));
		message.setCharset(hnaPayConfig.get("HNAPAY.CHARSET"));
		message.setSignType(hnaPayConfig.get("HNAPAY.SIGNTYPE"));
		if(BisPayCheckUtils.checkExternalOrderID(message.getOrderId())){
			 if(BankConstants.BANK_LOGO_CEB.equals(message.getBank())){
					message.setOrgCode("ceb");
				}else if(BankConstants.BANK_LOGO_BOCOM.equals(message.getBank())){
					message.setOrgCode("comm");
				}else if(BankConstants.BANK_LOGO_BOC.equals(message.getBank())){
					message.setOrgCode("boc");
				}else if(BankConstants.BANK_LOGO_PAB.equals(message.getBank())){
					message.setOrgCode("sdb");
				}else if(BankConstants.BANK_LOGO_GDB.equals(message.getBank())){
					message.setOrgCode("gdb");
				}else if(BankConstants.BANK_LOGO_CIB.equals(message.getBank())){
					message.setOrgCode("cib");
				}else if(BankConstants.BANK_LOGO_CITIC.equals(message.getBank())){
					message.setOrgCode("ecitic");
				}else if(BankConstants.BANK_LOGO_ABC.equals(message.getBank())){
					message.setOrgCode("abc");
				}else if(BankConstants.BANK_LOGO_CMB.equals(message.getBank())){
					message.setOrgCode("cmb");
				}
			 
		}
		message.setPartnerID(hnaPayConfig.get("HNAPAY."+message.getOrgCode().toUpperCase()+".PARTERID"));
		message.setPlainMessage(buildQueryMessage(message));
		BankLogUtils.printB2CManagerQuerySendLog(message, message.getPlainMessage());
		// 订单查询请求
		message = (HnaPayMessageQuery) hnaPayBankServiceClient.query(message);
		message.setOutStlmCd(BankConstants.BANK_LOGO_HNAPAY);
		BankLogUtils.printB2CManagerQueryReturnLog(message);
		return message;
	}
	
	/**
	 * 组装签名明文
	 * 
	 * @param message
	 * @return
	 */
	private String buildSignMessage(HnaPayMessage message) {
		StringBuffer sb = new StringBuffer("");
		String pkeyDes=hnaPayConfig.get("HNAPAY."+message.getOrgCode().toUpperCase()+".SIGNKEY");
		String pkey;
		try {
			pkey = KeyUtil.decryptDES(pkeyDes, message.getPrivateKeyPath());
			sb.append("version=").append(message.getVersion());
			sb.append("&serialID=").append(message.getSerialID());
			sb.append("&submitTime=").append(message.getSubmitTime());
			sb.append("&failureTime=").append(message.getFailureTime());
			sb.append("&customerIP=").append(message.getCustomerIP());
			sb.append("&orderDetails=").append(message.getOrderDetails());
			sb.append("&totalAmount=").append(message.getTotalAmount());
			sb.append("&type=").append(message.getType());
			sb.append("&buyerMarked=").append(message.getBuyerMarked());
			sb.append("&payType=").append(message.getPayType());
			sb.append("&orgCode=").append(message.getOrgCode());
			sb.append("&currencyCode=").append(message.getCurrencyCode());
			sb.append("&directFlag=").append(message.getDirectFlag());
			sb.append("&borrowingMarked=").append(message.getBorrowingMarked());
			sb.append("&couponFlag=").append(message.getCouponFlag());
			sb.append("&platformID=").append(message.getHnaPlatformID());
			sb.append("&returnUrl=").append(message.getReturnUrl());
			sb.append("&noticeUrl=").append(message.getNoticeUrl());
			sb.append("&partnerID=").append(message.getPartnerID());
			sb.append("&remark=").append(message.getRemark());
			sb.append("&charset=").append(message.getCharset());
			sb.append("&signType=").append(message.getSignType());
			// 商户签名密钥
			sb.append("&pkey=").append(pkey);
			return sb.toString();
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}

	/**
	 * 组装验签所需签名明文
	 * 
	 * @param message
	 * @return
	 */
	private String buildVerifyPlain(HnaPayMessage message) {
		StringBuffer sb = new StringBuffer();
		String pkeyDes=hnaPayConfig.get(message.getPartnerID());
		try{
			String pkey = KeyUtil.decryptDES(pkeyDes, message.getPrivateKeyPath());
			sb.append(message.getPlainMessage()).append("&pkey=").append(pkey);
			return sb.toString();
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 组装订单查询签名明文
	 * 
	 * @param message
	 * @return
	 */
	private String buildQueryMessage(HnaPayMessageQuery message) {
		StringBuffer sb = new StringBuffer("");
		String pkeyDes=hnaPayConfig.get("HNAPAY."+message.getOrgCode().toUpperCase()+".SIGNKEY");
		try{
			String pkey = KeyUtil.decryptDES(pkeyDes, message.getPrivateKeyPath());
			sb.append("version=").append(message.getVersion());
			sb.append("&serialID=").append(message.getSerialID());
			sb.append("&mode=").append(message.getMode());
			sb.append("&type=").append(message.getQueryType());
			sb.append("&orderID=").append(message.getBankOrderId());
			sb.append("&beginTime=").append(message.getBeginTime());
			sb.append("&endTime=").append(message.getEndTime());
			sb.append("&partnerID=").append(message.getPartnerID());
			sb.append("&remark=").append(message.getRemark());
			sb.append("&charset=").append(message.getCharset());
			sb.append("&signType=").append(message.getSignType());
			// 商户签名密钥
			sb.append("&pkey=").append(pkey);
			return sb.toString();
		}catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

}
